<template>
  <div class="dataSource">
    <el-divider content-position="left">
      <i></i>数据来源
    </el-divider>
    <el-form ref="form" :model="dataSource" :rules="formRules" label-width="120px">
      <el-form-item label="数据库类型" prop="databaseType">
        <el-select v-model="dataSource.databaseType" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseTypeEvent">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择数据源" prop="database">
        <el-select v-model="dataSource.database" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseDatabaseEvent">
          <el-option v-for="item in databaseOptions" :key="item.id" :label="item.datasourceName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择数据表" v-if="mode==='simpleTable' || mode==='online'" prop="tableName">
        <el-select v-model="dataSource.tableName" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseTableEvent()">
          <el-option v-for="item in tableOptions" :key="item.tableName" :label="item.tableName" :value="item.tableName"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div v-if="mode==='simpleTable' || mode==='online'">
      <el-divider content-position="left">
        <i></i>字段列表
      </el-divider>
      <div class="tableBox">
        <znxd-list :column="column" :page="page" :tableData="tableData" :pagination="false" :select="true" :initData="initSelection" @handlePageChange="handlePageChange(page)" @handleGetSelection="handleGetSelection"></znxd-list>
      </div>
    </div>
    <div v-else-if="mode==='multilist'">
      <el-divider content-position="left">
        <i></i>数据表
      </el-divider>
      <div class="tableBox transfer">
        <!-- :filter-method="filterMethod" -->
        <el-transfer filterable :titles="['数据表','已选']" filter-placeholder="请输入" v-model="dataSource.multilistData" :data="tableSourceData"></el-transfer>
      </div>
    </div>
  </div>
</template>
<script>
import { getDictionSelf } from "@/utils/config.js";
import { typeGetDataSource } from "@/api/dataset/database.js";
import { getTables, getColumnsType } from "@/api/dataset/table.js";
import { selectDictionaryByType } from "@/api/dict";

export default {
  components: {},
  data() {
    return {
      dataSource: {},
      // 数据库类型字典
      typeOptions: [
        // {
        //   label: "mysql",
        //   value: "mysql"
        // },
        // {
        //   label: "oracle",
        //   value: "oracle"
        // },
        // {
        //   label: "sqlserver",
        //   value: "sqlserver"
        // },
        // {
        //   label: "postgresql",
        //   value: "postgresql"
        // },
        // {
        //   label: "dm",
        //   value: "dm"
        // }
      ],
      databaseOptions: [],
      tableOptions: [],
      page: {
        pageNo: 1, // 当前位于哪页
        pageSize: 8, // 1页显示多少条
        total: 0
      },
      // 单表字段选择
      tableData: [],
      // 列表配置
      column: [
        {
          align: "center",
          name: "columnName",
          label: "字段名称"
        },
        {
          align: "center",
          name: "columnMemo",
          label: "字段别名"
        },
        {
          align: "center",
          name: "columnType",
          label: "字段类型"
        },
        {
          align: "center",
          name: "columnLong",
          label: "字段长度"
        }
      ],
      initSelection: [],
      // 多表选择
      tableSourceData: [],
      // initTableSourceData: []
      formRules: {}
    };
  },
  props: {
    initData: Object,
    mode: String
  },
  watch: {
    dataSource: {
      deep: true,
      handler: function (val) {
        console.log("dataSource", val);
        this.$emit("input", val);
      }
    },
    // "dataSource.multilistData": function (val) {
    //   // if (val) {
    //   //   let arrTables = [];
    //   //   val.map((x) => {
    //   //     let obj = this.tableOptions.filter((_item) => _item.tableName === x);
    //   //     arrTables.push(obj[0]);
    //   //   });
    //   //   this.dataSource.tables = arrTables;
    //   // }
    //   console.log("dataSource.multilistData", val);
    // },
    initData: {
      deep: true,
      handler: async function (obj) {
        // this.$refs.form.resetFields();
        // console.log("initData datasource", obj);
        if (obj.readerColumns) { this.initSelection = [...obj.readerColumns]; }
        this.dataSource = {
          databaseType: obj.readerDatasourceType,
          database: obj.readerDatasourceId
          // tableName: obj.readerTables.length > 0 ? obj.readerTables[0] : "",
        };
        if (this.mode === "simpleTable" || this.mode === "online") {
          this.dataSource.selection = obj.readerColumns;
          this.dataSource.tableName = obj.readerTables;
        } else if (this.mode === "multilist") {
          let arrData = [];
          obj.readerTables.map((x) => {
            arrData.push(x.tableName);
          });
          this.$set(this.dataSource, "multilistData", arrData)
          // console.log("multilistData", arrData);
          // this.dataSource.multilistData = arrData;
        }
        await this.chooseTypeEvent();
        await this.chooseDatabaseEvent();
        await this.chooseTableEvent(true);
        let _this = this;
        setTimeout(function () {
          _this.$refs.form.clearValidate();// 消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
        }, 30);
      }
    },
    tableOptions(val) {
      let arrData = [];
      val.map((x) => {
        let obj = {
          ...x,
          label: x.tableName,
          key: x.tableName
        };
        arrData.push(obj);
      });
      this.tableSourceData = arrData;
      // console.log(this.tableSourceData);
    }
  },
  methods: {
    async chooseTypeEvent() {
      // console.log("chooseTypeEvent");
      // console.log("this.dataSource.databaseType", this.dataSource.databaseType);
      if (!this.dataSource.databaseType) { return }
      let obj = {
        tableType: this.dataSource.databaseType
      };
      await typeGetDataSource(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.databaseOptions = data.content;
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    async chooseDatabaseEvent() {
      if (!this.dataSource.database) { return }
      let obj = {
        datasourceId: this.dataSource.database
      };
      let databaseName = getDictionSelf(
        this.databaseOptions,
        this.dataSource.database,
        "id",
        "databaseName"
      );
      this.$set(this.dataSource, "databaseName", databaseName);
      await getTables(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.tableOptions = data.content;
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    async chooseTableEvent(isFirst) {
      if (!this.dataSource.tableName) { return }
      let obj = {
        datasourceId: this.dataSource.database,
        tableName: this.dataSource.tableName
      };
      await getColumnsType(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.tableData = data.content;
          this.page.total = data.total;
          if (!isFirst) {
            this.initSelection = [];
          }
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    handlePageChange(page) {
      this.page = page;
      this.chooseTableEvent();
    },
    handleGetSelection(data) {
      this.dataSource = {
        ...this.dataSource,
        selection: data
      }
    },
    // 校验数据
    validateForm() {
      let flag = true;

      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
          return flag;
        }
      });

      switch (this.mode) {
        case "simpleTable":
          if (!this.dataSource.selection || this.dataSource.selection.length === 0) {
            flag = false;
            this.$message({
              message: "字段列表不能为空",
              type: "error"
            });
            return flag;
          }
          break;
        case "online":
          if (!this.dataSource.selection || this.dataSource.selection.length === 0) {
            flag = false;
            this.$message({
              message: "字段列表不能为空",
              type: "error"
            });
            return flag;
          }
          break;
        case "multilist":
          if (!this.dataSource.multilistData || this.dataSource.multilistData.length === 0) {
            flag = false;
            this.$message({
              message: "字段列表不能为空",
              type: "error"
            });
            return flag;
          }
          break;
        default:
          break;
      }

      return flag;
    },
    setRules() {
      switch (this.mode) {
        case "simpleTable":
          this.formRules = {
            databaseType: [{ required: true, message: "不能为空" }],
            database: [{ required: true, message: "不能为空" }],
            tableName: [{ required: true, message: "不能为空" }]
          }
          break;
        case "online":
          this.formRules = {
            databaseType: [{ required: true, message: "不能为空" }],
            database: [{ required: true, message: "不能为空" }],
            tableName: [{ required: true, message: "不能为空" }]
          }
          break;
        case "multilist":
          this.formRules = {
            databaseType: [{ required: true, message: "不能为空" }],
            database: [{ required: true, message: "不能为空" }]
          }
          break;
        default:
          break;
      }
    },
    // filterMethod(query, item) {
    //   if (query) { return item.columnName.indexOf(query) > -1; }
    // }
    // import { selectDictionaryByType } from "@/api/dict";
    getDBType() {
      selectDictionaryByType({ type: "dbType" })
        .then((res) => {
          let data = res.data;
          if (data.code === 200) {
            let options = [];
            data.data.map((x) => {
              options.push({ label: x.value, value: x.value });
            });
            this.typeOptions = options;
            // this.initForm();
          } else {
            // this.$message.error(data.msg);
          }
        })
        .catch(() => {
          // this.$message.error("操作失败");
        });
    }
  },
  mounted() {
    this.getDBType();
    if (this.initData.readerColumns) { this.initSelection = [...this.initData.readerColumns]; }
    this.setRules();
  }
};
</script>
<style lang="scss" scoped>
.dataSource {
  .el-divider__text.is-left {
    left: 0;
    display: flex;
    flex-direction: row;
    > i {
      display: block;
      width: 3px;
      height: 14px;
      background: #128df3;
      margin-right: 5px;
    }
  }
  .tableBox {
    padding-left: 40px;
  }
  .transfer {
    width: 800px;
    // max-height: 420px;
    // border: 1px solid red;
  }
}
</style>
<style lang="scss">
.dataSource {
  .transfer {
    .el-transfer-panel {
      width: 380px;
      .el-transfer-panel__item {
        width: 90%;
      }
    }
    .el-transfer-panel__body {
      height: 346px;
    }
    .el-transfer-panel__list {
      height: 300px;
    }
  }
}
</style>
